//获取start元素
let startBtn =document.getElementById("start");
//给start元素添加一个单击事件,单击时去执行start函数
startBtn.addEventListener('click' ,start);
//获取倒计时进度条
let progressBar = document.getElementById("progress_bar");

function start() {
    //倒计时
    countDown();
    //开始按钮消失
    startBtn.style.display = "none";
    //出现狼
    showWolf();
}

//给倒计时命名
let countDownTimer;
//给游戏时间结束命名
let gameOverTimer = false;
//倒计时函数
function countDown() {
    countDownTimer = setInterval(function(){
        //获取倒计时进度条的宽度
        let width = getComputedStyle(progressBar).width;
        //当宽度为0时停止定时器
        if (parseInt(width) <= 0) {
            clearInterval(countDownTimer);
            gameOverTimer = true;
        }
        //让倒计时进度条的宽度减少
        progressBar.style.width = parseInt(width) - 2 + "px";
    }, 100);
}

//狼移动的定时器
let wolfMoveTimer;

//狼逐渐显现的定时器
let wolfChangeTimer;

//出现狼的函数
function showWolf() {
    //获取存放狼的div
    let wolfDiv = document.getElementById("wolf_box");
    //创建狼的图片元素
    let wolfImg = document.createElement("img");
    wolfMoveTimer = setInterval(function () {
        if (gameOverTimer) {
            clearInterval(wolfMoveTimer);
        } else {
            //设置狼的位置
            wolfImg.style.top = getPosition().top;
            wolfImg.style.left = getPosition().left;
            //设置狼的类型
            let wolfType = getWolf();
            //设置图片显示内容
            let i = 0;
            wolfChangeTimer = setInterval(function () {
                if (i <= 5) {
                    wolfImg.src = `/images/${wolfType}${i}.png`;
                    i++;
                } else {
                    clearInterval(wolfChangeTimer);
                    i = 0;
                }
            }, 30)
        }
    }, 500);
//把狼的图片元素添加为wolfDiv元素的子元素
    wolfDiv.appendChild(wolfImg);
}

//狼的位置函数
function getPosition() {
    let arrayPosition = [
        {left: "98px", top: "115px"},
        {left: "17px", top: "160px"},
        {left: "15px", top: "220px"},
        {left: "30px", top: "293px"},
        {left: "122px", top: "273px"},
        {left: "207px", top: "295px"},
        {left: "200px", top: "211px"},
        {left: "187px", top: "141px"},
        {left: "100px", top: "185px"}
    ];
    let index = Math.floor(Math.random() * arrayPosition.length);
    return arrayPosition[index];
}

//狼的类型函数
function getWolf() {
    return Math.floor(Math.random() * 10) % 2 === 0 ? "h" : "x";
}



